--
-- BIN2C.LUA
--
-- Convert files to byte arrays for automatic loading with lua_dobuffer
--
-- Based on 'etc/bin2c.c' of Lua 5.0.1 sources by:
--      Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br)
--
-- Fixed so that subdirectory names are not included in debug info:
--      Asko Kauppi (asko.kauppi@sci.fi)
--
-- Fixed for multiple files with Lua 5.1 by:
--      Olivier Gournet (victor)


--
local function dump( f, id )
    local str= "static const unsigned char B"..id.."[]={\n"


    while true do
        for n=1,20 do
            local c= f:read(1)
            if not c then
                print( str.."\n};\n" ); return  -- the end
            end
            str= str.. string.format( "%3u,", string.byte(c) )
        end
        print(str)
        str= ""
    end
end


--
local function fdump( fn, id )
    --
    local f= io.open( fn, "rb" )    -- must open as binary

    if not f then
        error( "bin2c: cannot open "..fn )
    else
        print( "/* "..fn.." */" )
        dump( f, id )
        f:close()
    end
end


--
local function emit( fn, id )
   local _,_, base= string.find( fn, ".+[/\\](.-)$" ) -- remove path
   print( ' if (luaL_loadbuffer(l_,(const char*)B' .. id .. ',sizeof(B' .. id .. '),"'
         .. (base or fn) .. '") ||' )
   print( '     lua_pcall(l_, 0, 0, 0)) {' )
   print( '   fprintf(stderr, "[Lua] can\'t load ' .. (base or fn) .. '");' )
   print( ' }' )

end

--
local function main( argv )
    --
    print "/* code automatically generated by bin2c -- DO NOT EDIT */"
    print "{"

   if not argv[1] then -- use stdin (no params)
      --
      if os.getenv("WINDIR") then
         error "using stdin not allowed on Win32!" -- it wouldn't be binary
      end
      
      dump(io.stdin,0)
      emit("=stdin",0)
   else
      print "/*"
      print " #include'ing this file in a C program is equivalent to calling"
      for _,v in ipairs(argv) do
         print( ' lua_dofile(l_,"'.. string.gsub(v,'\\','\\\\')..'");' )
      end
      print "*/"
      for i,v in ipairs(argv) do fdump(v,i) end
      for i,v in ipairs(argv) do emit(v,i) end
   end
   
   print "}"
   return 0
end

return main(arg)
